<?php

/**
 * 
 * @author 
 * @version 
 *
 */

require_once 'Zend/Controller/Action.php';

class AuthController extends Zend_Controller_Action
{
	/**
	 * @var Zend_Form
	 */
	protected $_formAuth;

	public function init()
	{

	}

	/**
	 * The default action - show the home page
	 */
	public function indexAction()
	{
		$this->_formAuth = $this->_getAuthForm();
		
		if ( $this->_request->isPost() ) {
			$this->_checkAuth();
		}

		$this->view->assign(array(
			'form'	=>	$this->_formAuth
		));
	}
	
	public function logoutAction()
	{}
	
	protected function _checkAuth()
	{
		$rawPost = $this->_request->getPost();
		if ( $this->_formAuth->isValid( $rawPost ) ) {
			$auth = Zend_Auth::getInstance();
			
			$db = Zend_Db_Table_Abstract::getDefaultAdapter();
			$authAdapter = new Zend_Auth_Adapter_DbTable(
				$db,
				'bcms_users',
				'identity',
				'credential',
				"MD5(CONCAT(?, credential_salt)) AND active = '1' AND status = '1'"
			);
			
			$authAdapter->setIdentity( $this->_formAuth->getValue( 'auth_identity' ) )
						->setCredential( $this->_formAuth->getValue( 'auth_credential' ) );

			$result = $auth->authenticate( $authAdapter );
			
			if ( $result->isValid() ) {
			 	$storage = $auth->getStorage();
			 	$resultObject = $authAdapter->getResultRowObject( null, array( 'credential', 'credential_salt' ) );
			 	$storage->write( $resultObject );
			 	
			 	$this->_helper->redirector( 'index', 'index' );
			} else {
				Zend_Debug::dump('asd');
				$this->_formAuth->markAsError();
				$this->_formAuth->addErrorMessage('sadas');
			}
		}
		
		return false;
	}
	
	/**
	 * Obtener el formulario de sesion
	 * 
	 * @return Zend_Form 
	 */
	protected function _getAuthForm()
	{
		$form = new Bcmsx_Form_Auth();
		
		return $form;
	}

}